package org.xiaojl.xcloud.tools.gateway.filter.pre;

import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.xiaojl.xcloud.tools.gateway.kit.FilterKit;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;

/**  
 * <p>Title: CorsFilter</p>  
 *
 * <p>Description: 解决跨越请求问题</p>  
 *
 * @author jilong.xiao  
 * @date 2018年4月23日  
 */
@Component
public class CorsFilter extends ZuulFilter {
	@Override
	public boolean shouldFilter() {
		return FilterKit.isFilterFlag(RequestContext.getCurrentContext());
	}

	@Override
	public Object run() {
		final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
		CorsConfiguration conf = new CorsConfiguration();
		conf.setAllowCredentials(true); //允许cookies跨域
		conf.addAllowedOrigin("*"); //#允许向该服务器提交请求的URI，*表示全部允许，在SpringMVC中，如果设成*，会自动转成当前请求头中的Origin  
		conf.addAllowedHeader("*");// #允许访问的头信息,*表示全部
		conf.setMaxAge(18000L);// 预检请求的缓存时间（秒），即在这个时间段里，对于相同的跨域请求不会再预检了  
		conf.addAllowedMethod("OPTIONS");// 允许提交请求的方法，*表示全部允许  
		conf.addAllowedMethod("HEAD");  
		conf.addAllowedMethod("GET");// 允许Get的请求方法  
		conf.addAllowedMethod("PUT");  
        conf.addAllowedMethod("POST");  
        conf.addAllowedMethod("DELETE");  
        conf.addAllowedMethod("PATCH");  
        
		source.registerCorsConfiguration("/**", conf);
		return null;
	}

	@Override
	public String filterType() {
		return FilterConstants.PRE_TYPE;
	}

	@Override
	public int filterOrder() {
		return 100;
	}

}
